/**
 * @class cnzz统计
 * @description cnzz统计
 * @constructor
 */

import BaseContext from '../context';
export default class CNZZ extends BaseContext {
  constructor(app, options) {
    super(app, options);
    this.modules = options.modules || Object.create(null);
  }

  init() {
    this.loadHtml();
    this.initEvent();
  }

  initEvent() {
    this.listener({
      chapterIndexChange: this.sendCNZZEvent.bind(this)
    })
  }

  loadHtml() {
    const template = this.template;
    if (template.cnzz) {
      const { comicName, comicId } = this.comicInfo;
      const strNodes = template.cnzz({
        comicName,
        comicId,
      });
      const nodes = this.util.createDocumentHtml(strNodes);
      this.container.append(nodes);
    }
  }

  get cnzzModule() {
    const { cnzz } = this.modules;
    if (cnzz) {
      return cnzz;
    }
  }

  sendCNZZEvent(index) {
    if (!window.cnzz) {
      return;
    }
    const { chapterList } = this.currentChapter;
    const image = chapterList.find(item => item.chapterIndex === index && !item.isPushEvent);
    if (!image) {
      return;
    }
    if (this.cnzzModule) {
      this.cnzzModule.push(cnzz)
    }
    if (window._czc) {
      // 发子站
      window._czc.push(['_trackPageview', location.href.replace(location.origin, ''), location.href]);
      image.isPushEvent = true;
    }
  }
}
